/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-11-11 20:17:00
 * Last Modified: 2016-12-30 10:05:39
 * File Name: controllers/userfrofile.go
 * Description:
 */
package controllers

import (
	"encoding/json"

	"passport/avatar"
	"passport/errorcode"
	"passport/user"

	log "github.com/cihub/seelog"
)

type UserProfileController struct {
	LoginedController
}

/*
	用户信息查询
*/
func (p *UserProfileController) QueryUserProfile() {
	defer p.Output("QueryUserProfile")

	ui, uiErr := user.GetUserService().GetAllUserInfo(p.UserId)
	if uiErr != nil {
		log.Errorf("query user profile failed for uid: %s, msg: %s", p.UserId, uiErr.Error())
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
		return
	}

	if ui == nil {
		log.Errorf("query user profile get empty for uid: %s", p.UserId)
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "该用户不存在"
		return
	}

	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["mobile"] = ui.Mobile
	p.Resp["nick_name"] = ui.NickName
	p.Resp["gender"] = ui.Gender
	if len(ui.Avatar) == 32 { //自有的
		p.Resp["avatar"], _ = avatar.GetAvatarURL(ui.Avatar)
	} else { //第三方地址
		p.Resp["avatar"] = ui.Avatar
	}
	p.Resp["slogan"] = ui.Slogan
	p.Resp["region_code"] = ui.RegionCode
	p.Resp["region_addr"] = ui.RegionAddr
	p.Resp["birthday"] = ui.Birthday
	p.Resp["invite_code"] = ui.InviteCode
	p.Resp["invite_by"] = ui.InviteBy
	p.Resp["vuid"] = ui.Vuid
	p.Resp["reg_time"] = ui.InsertTime
	p.Resp["reg_plat"] = ui.RegPlat
}

/*
	更新用户信息
*/
func (p *UserProfileController) UpdateUserProfile() {
	defer p.Output("UpdateUserProfile")

	body := p.Ctx.Input.RequestBody
	log.Debugf("recv %s", string(body))
	data := make(map[string]interface{})
	if err := json.Unmarshal(body, &data); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	code, msg := user.GetUserService().UpdateUserProfileInfo(p.UserId, data)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
}

/*
	上传用户头像
*/
func (p *UserProfileController) AvatarBase64Upload() {
	defer p.Output("AvatarBase64Upload")

	body := p.Ctx.Input.RequestBody
	//log.Debugf("recv body [%s]", string(body))
	reqBody := &avatar.AvatarBase64UploadReq{}
	if err := json.Unmarshal(body, reqBody); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	code, msg, res := avatar.GetAvatarService().Base64Upload(reqBody)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
	if code == errorcode.EC_GL_SUCCESS {
		p.Resp["url"] = res.Url
		p.Resp["hash"] = res.Hash
		go func() {
			uinfoChanger := user.NewUserInfoChanger(p.UserId)
			uinfoChanger.SetAvatar(res.Hash)
			uinfoChanger.Save()
		}()
	}
}
